<div class="container">

    <div class="page-header">
        <div class="row">
            <h1 class="span8"><? if($post_action=='EDIT'){ echo 'Edit';}else echo 'Add';?> <?=ucfirst($post_type)?></h1>
            <span class="span4">

            </span>
        </div>


    </div>

    <div class="row">

        <div class="span8">

            <form class="form-horizontal-qtrans" id="post" method="post" action="javascript:" name="post">

                <input type="hidden" value="<?=$post_type;?>" name="post_type" id="post_type">
                <input type="hidden" value="<?=$post_action;?>" name="post_action" id="post_action">

                <?        
                    if($post_action=='EDIT'){?>
                    <input type="hidden" value="<?=$post['ID'];?>" name="post_ID" id="post_ID">
                    <?}
                ?>

                <fieldset>


                    <div id="post-body">

                        <div id="post-body-content">

                            <!--THIS CONTENT WILL BE HIDDEN BY JAVASCRIPT LANGUAGE-->
                            <div id="titlediv">

                                <div id="titlewrap">

                                    <input type="text" autocomplete="off" id="title" value="<?if($post_action=='EDIT')echo $post['post_title'];?>" tabindex="1" size="30" name="post_title">

                                </div>

                                <div class="inside"></div>

                            </div>
                            <!--/THIS CONTENT WILL BE HIDDEN BY JAVASCRIPT LANGUAGE-->

                            <div class="postarea" id="postdivrich">

                                <div class="wp-editor-wrap tmce-active" id="wp-content-wrap">

                                    <div class="wp-editor-tools" id="wp-content-editor-tools">

                                    </div>

                                    <div id="wp-content-editor-container" class="wp-editor-container">

                                        <!--THIS CONTENT WILL BE HIDDEN BY JAVASCRIPT LANGUAGE-->
                                        <textarea class="wp-editor-area" rows="20" tabindex="1" cols="40" name="content" id="content">
                                            <?if($post_action=='EDIT')echo $post['content'];?>
                                        </textarea>
                                        <!--/THIS CONTENT WILL BE HIDDEN BY JAVASCRIPT LANGUAGE-->

                                        <textarea id="qtrans_textarea_content" name="qtrans_textarea_content" tabindex="2" rows="20" cols="40" style="display:none" onblur="qtrans_save(this.value);"></textarea>

                                    </div>

                                </div>

                            </div>

                        </div>

                    </div>

                    <div class="parent well" style="margin-top: 23px; margin-bottom: 23px;">
                        <h3 style="padding-left: 0;"><?=ucfirst($post_type)?> properties</h3>
                        <label for="parent_id" class="screen-reader-text">Parent</label>
                        <select id="parent_id" name="parent_id">
                            <option value="0" selected="selected">(no parent)</option>
                            <?  
                                $selected = '';
                                foreach($all_posts as $one_post): ?>
                                <? if($one_post['ID']!=$post['ID']){ ?>
                                    <? if($post_action=='EDIT'){                                
                                            if($one_post['ID']==$post['parent_ID']){
                                                $selected = 'selected="selected"';
                                            }  
                                        }

                                    ?>
                                    <option value="<?=$one_post['ID']?>" class="level-0" <?echo $selected;?>><?=$one_post['name']?></option>
                                    <?}?>
                                <? 
                                    $selected='';
                                    endforeach; ?>
                        </select>
                    </div>

                    <div class="form-actions">

                        <div class="row">

                            <? if($post_action=='EDIT'):?>       

                                <div class="span1-5" id="delete-action">
                                    <a class="submitdelete deletion delete_post" href="<?=base_url($link.'/delete/'.$post['ID'].'?post_type='.$post_type)?>">Move to Trash</a>
                                </div>

                                <? endif; ?> 

                            <span class="<? if($post_action=='EDIT'){echo 'span2 ml-15';}else echo 'span4'; ?> save"><button class="btn btn-primary" type="submit"><i class="icon-white icon-download-alt"></i> Save changes</button></span>
                            <span class="span4 loader"><img id="ajax-loading" class="ajax-loading" src="<?=base_url()?>assets/img/backgnds/loading.gif" style="visibility: hidden;"></span>
                        </div>

                    </div>

                </fieldset>
            </form>

        </div>

        <div class="span4">

            <div class="hero-unit">
                <h3><?=ucfirst($post_type)?></h3>
                <p>
                    <a class="btn btn-large" href="<?=base_url($link.'/view_all?post_type='.$post_type)?>">
                        <i class="icon-list-alt"></i> View All <?=ucfirst($post_type)?>
                    </a>
                </p>
            </div>

        </div>
    </div>

</div> <!-- /container -->

<!--INPUT TITLE & TINY MCE QTRANS PROCEESSING--> 
<script type="text/javascript">
    var wp_languages = new Array();
    var wp_languages_short = new Array();
    <?

        $i=0;
        foreach(config_item('wp_languages') as $key=>$value){

        ?>

        wp_languages['<?=$i?>'] = '<?=$value?>';
        wp_languages_short['<?=$i?>'] = '<?=$key?>';

        <?
            $i++;
        }
    ?>
</script>

<!--<script src="<?=base_url()?>assets/js/qtrans/title.js" type="text/javascript"></script>-->

<!--qTrans Title.js-->
<script type="text/javascript">

    function qtrans_editorInit1() {

        qtrans_isArray = function(obj) {
            if (obj.constructor.toString().indexOf('Array') == -1)
                return false;
            else
                return true;
        }

        String.prototype.xsplit = function(_regEx){
            // Most browsers can do this properly, so let them — they'll do it faster
            if ('a~b'.split(/(~)/).length === 3) { return this.split(_regEx); }

            if (!_regEx.global)
                { _regEx = new RegExp(_regEx.source, 'g' + (_regEx.ignoreCase ? 'i' : '')); }

            // IE (and any other browser that can't capture the delimiter)
            // will, unfortunately, have to be slowed down
            var start = 0, arr=[];
            var result;
            while((result = _regEx.exec(this)) != null){
                arr.push(this.slice(start, result.index));
                if(result.length > 1) arr.push(result[1]);
                start = _regEx.lastIndex;
            }
            if(start < this.length) arr.push(this.slice(start));
            if(start == this.length) arr.push(''); //delim at the end
            return arr;
        };

        qtrans_split = function(text) {
            var split_regex = /(<!--.*?-->)/gi;
            var lang_begin_regex = /<!--:([a-z]{2})-->/gi;
            var lang_end_regex = /<!--:-->/gi;
            var morenextpage_regex = /(<!--more-->|<!--nextpage-->)+$/gi;
            var matches = null;
            var result = new Object;
            var matched = false;


            jQuery.each(wp_languages_short, function(key, value) { 
                    result[value] = '';
            });


            var blocks = text.xsplit(split_regex);
            if(qtrans_isArray(blocks)) {
                for (var i = 0;i<blocks.length;i++) {
                    if((matches = lang_begin_regex.exec(blocks[i])) != null) {
                        matched = matches[1];
                    } else if(lang_end_regex.test(blocks[i])) {
                        matched = false;
                    } else {
                        if(matched) {
                            result[matched] += blocks[i];
                        } else {

                            jQuery.each(wp_languages_short, function(key, value) { 
                                    result[value] += blocks[i];
                            });

                        }
                    }
                }
            }
            for (var i = 0;i<result.length;i++) {
                result[i] = result[i].replace(morenextpage_regex,'');
            }
            return result;
        }        

        qtrans_use = function(lang, text) {
            var result = qtrans_split(text);
            return result[lang];
        }

        qtrans_integrate_title = function() {
            var t = document.getElementById('title');

            jQuery.each(wp_languages_short, function(key, value) { 

                    t.value = qtrans_integrate(value,document.getElementById('qtrans_title_'+value).value,t.value);

            });

        }

        qtrans_integrate = function(lang, lang_text, text) {
            var texts = qtrans_split(text);
            var moreregex = /<!--more-->/i;
            var text = '';
            var max = 0;
            var morenextpage_regex = /(<!--more-->|<!--nextpage-->)+$/gi;

            texts[lang] = lang_text;

            jQuery.each(wp_languages_short, function(key, value) { 

                    texts[value] = texts[value].split(moreregex);
                    if(!qtrans_isArray(texts[value])) {
                        texts[value] = [texts[value]];
                    }
                    if(max < texts[value].length) max = texts[value].length;

            });

            for(var i=0; i<max; i++) {
                if(i >= 1) {
                    text += '<!--more-->';
                }

                jQuery.each(wp_languages_short, function(key, value) { 

                        if(texts[value][i] && texts[value][i]!=''){
                            text += '<!--:'+value+'-->';
                            text += texts[value][i];
                            text += '<!--:-->';
                        }

                });

            }
            text = text.replace(morenextpage_regex,'');
            return text;
        }

    }

</script>

<!--Initialize qTrans Title-->
<script type="text/javascript">

    jQuery(document).ready(function() {

            qtrans_editorInit1();

            // Create elements
            jQuery.each(wp_languages_short, function(key, value) {

                    //console.log('key:'+key+' -> value: '+value);

                    var td = document.getElementById('titlediv');
                    var qtd = document.createElement('div');
                    var h = document.createElement('h3');
                    var l = document.createTextNode('Title ('+wp_languages[key]+')');
                    var tw = document.createElement('div');
                    var ti = document.createElement('input');
                    var slug = document.getElementById('edit-slug-box');

                    ti.type = 'text';
                    ti.id = 'qtrans_title_'+value;
                    ti.tabIndex = '1';
                    ti.value = qtrans_use(value, document.getElementById('title').value);
                    ti.onchange = qtrans_integrate_title;
                    ti.className = 'qtrans_title_input';
                    h.className = 'qtrans_title';
                    tw.className = 'qtrans_title_wrap';

                    qtd.className = 'postarea';

                    h.appendChild(l);
                    tw.appendChild(ti);
                    qtd.appendChild(h);
                    qtd.appendChild(tw);
                    td.parentNode.insertBefore(qtd,td);

            });                                             

            document.getElementById('titlediv').style.display='none'; 

    });



</script>

<!--<script src="<?=base_url()?>assets/js/qtrans/tinymce.js" type="text/javascript"></script>-->

<!-- qTrans TinyMCE and Initialize-->
<script type="text/javascript">

    switchEditors.go = function(id, lang) {

        //console.log('switchEditors:'+lang)
        id = id || 'content';
        lang = lang || 'toggle';

        if ( 'toggle' == lang ) {
            if ( ed && !ed.isHidden() )
                lang = 'html';
            else
                lang = 'tmce';
        } else if( 'tinymce' == lang ) 
            lang = 'tmce';

        var inst = tinyMCE.get('qtrans_textarea_' + id);
        var vta = document.getElementById('qtrans_textarea_' + id);
        var ta = document.getElementById(id);
        var dom = tinymce.DOM;
        var wrap_id = 'wp-'+id+'-wrap';

        // update merged content
        if(inst && ! inst.isHidden()) {
            //tinyMCE.triggerSave();
            qtrans_save(tinyMCE.get('qtrans_textarea_content').getContent());
            //console.log(tinyMCE.get('qtrans_textarea_content').getContent())
        } else {
            qtrans_save(vta.value);
            //console.log('qtrans_save:')
        }


        // check if language is already active
        if(lang!='tmce' && lang!='html' && document.getElementById('qtrans_select_'+lang).className=='wp-switch-editor switch-tmce switch-html') {
            return;
        }

        if(lang!='tmce' && lang!='html') {
            //console.log(qtrans_get_active_language())
            document.getElementById('qtrans_select_'+qtrans_get_active_language()).className='wp-switch-editor';
            document.getElementById('qtrans_select_'+lang).className='wp-switch-editor switch-tmce switch-html';
        }                
        // switch content
        qtrans_assign('qtrans_textarea_'+id,qtrans_use(lang,ta.value));
    }

    qtrans_assign = function(id, text) {
        var inst = tinyMCE.get(id);
        var ta = document.getElementById(id);
        if(inst && ! inst.isHidden()) {
            text = switchEditors.wpautop(text);
            inst.execCommand('mceSetContent', null, text);
        } else {
            ta.value = text;
        }
    }

    qtrans_save = function(text) {
        //console.log('save')

        var ta = document.getElementById('content');

        ta.value = qtrans_integrate(qtrans_get_active_language(),text,ta.value);
        //console.log(ta.value)

        return ta.value;
    }

    qtrans_get_active_language = function() 
    {
        
       <? foreach(config_item('wp_languages') as $key=>$value): ?>        
        
        if(document.getElementById('qtrans_select_'+'<?=$key?>').className=='wp-switch-editor switch-tmce switch-html')
            return '<?=$key?>';

        <? endforeach; ?> 

    }

    // Create elements
    jQuery.each(wp_languages_short, function(key, value) {

            //console.log('key:'+key+' -> value: '+value);

            var bc = document.getElementById('wp-content-editor-tools');
            var mb = document.getElementById('wp-content-media-buttons');
            var ls = document.createElement('a');
            var l = document.createTextNode(wp_languages[key]);
            ls.id = 'qtrans_select_'+value;
            ls.className = 'wp-switch-editor';
            ls.onclick = function() { switchEditors.go('content',value); };
            ls.appendChild(l);
            bc.insertBefore(ls,mb);

    });

    var waitForTinyMCE = window.setInterval(function() {
            if(typeof(tinyMCE) !== 'undefined' && typeof(tinyMCE.get2) == 'function' && tinyMCE.get2('content')!=undefined) {
                content=jQuery('#content').val();
                tinyMCE.get2('content').remove();
                jQuery('#content').val(content);
                window.clearInterval(waitForTinyMCE);
            }

        }, 250);

    function qtrans_editorInit2() {

        //console.log(wp_languages_short[0])
        document.getElementById('qtrans_select_'+wp_languages_short[0]).className='wp-switch-editor switch-tmce switch-html';
        var text = document.getElementById('content').value;
        qtrans_assign('qtrans_textarea_content',qtrans_use(wp_languages_short[0],text));

    }

    if(typeof(wpOnload)!='undefined') wpOnload2 = wpOnload;

    jQuery(document).ready(function() {

            qtrans_editorInit2();

            jQuery('#qtrans_imsg').hide();

            jQuery('#content').hide();    

            // Activate TinyMCE if it's the user's default editor
            jQuery('#qtrans_textarea_content').show();

    });
</script>

<!--POST DELETE HANDLER--> 
<script type="text/javascript">
    jQuery(document).ready(function() {

            jQuery('.delete_post').live('click',function(){

                    var conf = confirm("Delete <?=ucfirst($post_type)?>?")
                    if (!conf){
                        return false;
                    }

                    window.location.href = jQuery(this).attr('href');

                    return false;

            });

    } );
</script>
<!--/POST DELETE HANDLER-->

<!--FORM SUBMIT HANDLER-->
<script>

    jQuery(document).ready(function() {       

            // Override default error message
            jQuery.validator.messages.required = "";

            // Override generation of error label
            $("#post").validate({
                    submitHandler: function(form) {

                        $('input[type=submit]', '#post').attr('disabled', 'disabled');

                        qtrans_save(tinyMCE.get('qtrans_textarea_content').getContent()); 
                        $('#ajax-loading').css('visibility','visible');

                        var form = $("#post");
                        var form_data = form.serialize();

                        $.ajax({
                                url: base_url+'<?=$link?>'+'/submit_post',
                                dataType: 'json',
                                type: "POST",
                                data: form_data,
                                success: function (data, textStatus, xhr) {
                                    jQuery('#ajax-loading').css('visibility','hidden');

                                    if(data.action==true){

                                        jQuery('.loader').html(data.msg);

                                        // REDIRECT
                                        function promo_show(){
                                            window.location.href = base_url+'<?=$link?>'+'/view_all?post_type=<?=$post_type?>'; 
                                        }
                                        window.setTimeout(function() { promo_show(); }, 1001);

                                    }else{

                                        $('#post').removeAttr('disabled');                             
                                        alert(data.msg)  
                                    }
                                },
                                error: function (xhr, textStatus, errorThrown) {
                                    alert('Error ocured...\n Server not found.');
                                    $('input[type=submit]', '#post').removeAttr('disabled');
                                    $('#ajax-loading').css('visibility','hidden');
                                }
                        });

                    },
                    errorPlacement: function(error, element){}
            });

            $('input[type=submit]', '#post').removeAttr('disabled'); 


    });

</script>
<!--/FORM SUBMIT HANDLER--> 